package lol.clann.bukkit.pluginboot.util;

import lol.clann.clannboot.annotation.inject.Inject;
import lol.clann.clannboot.annotation.svc.PostInstance;
import lol.clann.clannboot.annotation.svc.Service;
import lol.clann.clannboot.util.clazz.ClassUtils;
import lol.clann.clannboot.util.clazz.MethodFilter;
import lol.clann.clannboot.util.clazz.WrapClass;
import lol.clann.clannboot.util.clazz.WrapMethod;

/**
 * @author pyz
 * @date 2018/8/5 上午8:34
 */
@Service(priority = Integer.MAX_VALUE)
public class TileEntityUtils {

    public static final WrapClass classNMSTileEntity = ClassUtils.forName("{nms}.TileEntity");
    private WrapMethod writeToNBT;
//    private WrapMethod createAndLoadEntity;
    private WrapMethod readFromNBT;

    @Inject
    private NBTCompoundUtils nbtCompoundUtils;

    @PostInstance
    private void init() {
        writeToNBT = classNMSTileEntity.getMethod(MethodFilter.build().name("save", "writeToNBT").parameterType(NBTUtils.classNBTTagCompound));
        readFromNBT = classNMSTileEntity.getMethod(MethodFilter.build().returnVoid().parameterType(NBTUtils.classNBTTagCompound).index(0));
//        createAndLoadEntity = classNMSTileEntity.getMethod(MethodFilter.build().returnType(classNMSTileEntity).parameterType(NBTUtils.classNBTTagCompound).static_(true));
    }

    /**
     * @param nmsTileEntity
     * @return NBTTagCompound
     */
    public Object toCompound(Object nmsTileEntity) {
        Object tag = nbtCompoundUtils.newTagCompound();
        writeToNBT.invoke(nmsTileEntity, tag);
        return tag;
    }

//    /**
//     * @param nbtTag
//     * @return nmsTileEntity
//     */
//    public Object fromCompound(Object nbtTag) {
//        return createAndLoadEntity.invoke(null, nbtTag);
//    }

    public void fill(Object nmsTileEntity, Object nbtTag) {
        readFromNBT.invoke(nmsTileEntity, nbtTag);
    }
}
